const axios = require('axios')
const config = require('../config/axios.js')
const stream = require('node:stream')
const { TextDecoderStream } = require('node:stream/web')

const pattern = /{.*}/g

module.exports = function openai (req, res, next) {
  // 与前端的交互
  frontendInteraction(req, res, config)

  // 与openai api 的交互
  openaiInteraction(res, config)
}

function frontendInteraction (request, response, config) {
  response.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive'
  })
  response.flushHeaders()
  config.data.messages = request.body
  console.log(config.data.messages)
}

async function openaiInteraction (response, config) {
  try {
    const openaires = await axios(config)
    openaires.data.on('end', () => {
      response.end()
    })
    const openaistream = transform(openaires.data)
    for await (const chunk of handleChunk(openaistream)) {
      response.write(chunk)
      console.log(chunk)
    }
  } catch (error) {
    if (error.response) {
      // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
      console.log(error.response.data)
      console.log(error.response.status)
      console.log(error.response.headers)
    } else if (error.request) {
      // 请求已经成功发起，但没有收到响应
      // `error.request` 在浏览器中是 XMLHttpRequest 的实例，
      // 而在node.js中是 http.ClientRequest 的实例
      console.log(error.request)
    } else {
      // 发送请求时出了点问题
      console.log('Error', error.message)
    }
    response.end()
  }
}

function transform (nodestream) {
  return stream.Readable.toWeb(nodestream).pipeThrough(new TextDecoderStream())
}

async function * handleChunk (stream) {
  for await (const chunk of stream) {
    if (pattern.test(chunk)) {
      for (const json of chunk.match(pattern)) {
        const obj = JSON.parse(json)
        const text = obj.choices[0].delta
        if ('content' in text) {
          yield text.content
        }
      }
    } else {
      console.log('All data has been sent')
    }
  }
}
